<template>
    <div class="list-container">
        <div class='search-area'>
            <div class='search-left'>
                <div class='input-line'>
                    <span class='label'>搜索关键词：</span>
                    <el-input placeholder="请输入商户名" label='商户名' v-model="searchParams.keyword"/>
                </div>
                <div class='input-line'>
                    <span class='label'>产品状态：</span>
                    <el-select v-model="searchParams.status" placeholder="请选择">
                        <el-option label="全部" value=""></el-option>
                        <el-option label="已发布" value="1"></el-option>
                        <el-option label="草稿" value="2"></el-option>
                        <el-option label="定时发布" value="3"></el-option>
                    </el-select>
                </div>
                <div class='input-line'>
                    <span class='label'>显示类型：</span>
                    <el-select v-model="searchParams.viewType" placeholder="请选择">
                        <el-option label="全部" value=""></el-option>
                        <el-option label="PC端" value="1"></el-option>
                        <el-option label="移动端" value="2"></el-option>
                    </el-select>
                </div>
            </div>
            <div class='search-right'>
                <el-button type="primary" @click='onSearchClick'>查询</el-button>
                <el-button type="primary" @click='onDialogOpen'>新增产品</el-button>
            </div>
        </div>
        <el-table fit :data="tableData" style="width: 100%">
            <el-table-column
                prop="bannerPic"
                label="产品主图">
                <template slot-scope="scope">
                    <img class="thumbnail" :src="scope.row.bannerPic" alt="">
                </template>
            </el-table-column>
            <el-table-column
                prop="firstLevelTitle"
                label="一级标题">
            </el-table-column>
            <el-table-column
                prop="secondLevelTitle"
                label="二级标题">
            </el-table-column>
            <el-table-column
                prop="content"
                label="产品简介">
            </el-table-column>
            <el-table-column
                prop="jumpUrl"
                label="购买链接">
                <template slot-scope="scope">
                    <a :href="scope.row.jumpUrl" target="_blank">{{ scope.row.jumpUrl }}</a>
                </template>
            </el-table-column>
            <el-table-column
                prop="typeId"
                label="语言类型">
                <template slot-scope="scope">
                    <el-tag v-if="scope.row.languageType === 'ch'" type="warning">中文</el-tag>
                    <el-tag v-if="scope.row.languageType === 'en'" type="danger">英文</el-tag>
                    <el-tag v-if="scope.row.languageType === 'fan'" type="success">繁体</el-tag>
                </template>
            </el-table-column>
            <el-table-column
                prop="typeId"
                label="资讯状态">
                <template slot-scope="scope">
                    <el-tag v-if="scope.row.status === 1" type="success">已发布</el-tag>
                    <el-tag v-if="scope.row.status === 2">草稿</el-tag>
                    <el-tag v-if="scope.row.status === 3" type="info">定时发布</el-tag>
                    <el-tag v-if="scope.row.status === 3" type="info">{{ scope.row.publishTime }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column
                prop="detailText"
                label="产品详细介绍">
                <template slot-scope="scope">
                    <el-button type='primary' size='mini' @click='onDetailPreviewClick(scope.row.detailText)'>查看详细介绍</el-button>
                </template>
            </el-table-column>

            <el-table-column
                align='center'
                label="操作"
                width='200'>
                <template slot-scope="scope">
                    <div style='display: flex;align-items: center;flex-wrap: wrap'>
                        <el-button type='primary' size='mini' @click='onDeleteClick(scope.row.id)'>删除</el-button>
                        <el-button type='primary' size='mini' @click='handleModify(scope.row.id)'>修改</el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <div class='pagination'>
            <el-pagination
                background
                layout="prev, pager, next"
                :current-page='currentPage'
                :page-size='10'
                :total="total"
                @current-change='onPageChange'
            >
            </el-pagination>
        </div>

        <!--   新增产品弹框     -->
        <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" @close="onDialogClose()">
            <el-form ref="dataForm" :rules="rules" :model="addForm" label-width="80px">
                <el-form-item label="语言类型" prop="status">
                    <el-radio-group v-model="addForm.languageType">
                        <el-radio-button label="ch">中文</el-radio-button>
                        <el-radio-button label="en">英文</el-radio-button>
                        <el-radio-button label="fan">繁体</el-radio-button>
                    </el-radio-group>
                    <div class="upload-notice">产品相关内容，请所选择的语言类型！</div>
                </el-form-item>
                <el-form-item label="显示类型" prop="status">
                    <el-radio-group v-model="addForm.viewType">
                        <el-radio-button label="0">全端</el-radio-button>
                        <el-radio-button label="1">PC端</el-radio-button>
                        <el-radio-button label="2">移动端</el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="产品状态" prop="status">
                    <el-radio-group v-model="addForm.status">
                        <el-radio-button label="1">发布</el-radio-button>
                        <el-radio-button label="2">草稿</el-radio-button>
                        <el-radio-button label="3">定时发布</el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="发布时间" prop="status" v-if="addForm.status == 3">
                    <el-date-picker
                        v-model="addForm.publishTime"
                        type="datetime"
                        placeholder="选择日期时间">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="产品主图" prop="bannerPic">
                    <el-upload
                        action="http://8.137.53.59:8888/api/common/upload"
                        list-type="picture-card"
                        :limit="1"
                        :file-list="bannerPicList"
                        :before-upload="handleBeforeUpload"
                        :on-success="handleUploadSuccess"
                        :on-remove="handleRemove">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <div class="upload-notice">*图片尺寸：1920×980，或符合该宽高比例的图片</div>
                </el-form-item>
                <el-form-item label="缩略图" prop="thumbnailPic">
                    <el-upload
                        action="http://8.137.53.59:8888/api/common/upload"
                        list-type="picture-card"
                        :limit="1"
                        :file-list="thumbnailPicList"
                        :before-upload="handleBeforeUploadSmall"
                        :on-success="handleUploadSuccessSmall"
                        :on-remove="handleRemove">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <div class="upload-notice">*图片尺寸：304×304，或符合该宽高比例的图片</div>
                </el-form-item>
                <el-form-item label="一级标题" prop="firstLevelTitle">
                    <el-input v-model="addForm.firstLevelTitle" placeholder="一级标题"></el-input>
                </el-form-item>
                <el-form-item label="二级标题" prop="secondLevelTitle">
                    <el-input v-model="addForm.secondLevelTitle" placeholder="二级标题"></el-input>
                </el-form-item>
                <el-form-item label="产品简介" prop="content">
                    <el-input v-model="addForm.content" placeholder="产品简介"></el-input>
                </el-form-item>
                <el-form-item label="购买链接" prop="jumpUrl">
                    <el-input v-model="addForm.jumpUrl" placeholder="购买链接"></el-input>
                </el-form-item>
                <el-form-item label="产品详情" prop="productDetailDtoList">
                    <div class="detail-list-container" v-for="(detailListItem, index) in addForm.productDetailDtoList">
                        <el-form-item label="条目缩略">
                            <el-upload
                                action="http://8.137.53.59:8888/api/common/upload"
                                list-type="picture-card"
                                :limit="1"
                                :file-list="[{name: 'bannerPic'+index, url: detailListItem.thumbnailPic}]"
                                :before-upload="handleBeforeUploadSmall"
                                :on-success="(response, file, fileList) =>handleUploadSuccessSmallDetailItem(response, file, fileList, index)"
                                :on-remove="handleRemove">
                                <i class="el-icon-plus"></i>
                            </el-upload>
                            <div class="upload-notice">*图片尺寸：304×304，或符合该宽高比例的图片</div>
                        </el-form-item>

                        <el-form-item label="一级标题">
                            <el-input v-model="detailListItem.firstLevelTitle" placeholder="一级标题"></el-input>
                        </el-form-item>
                        <el-form-item label="二级标题">
                            <el-input v-model="detailListItem.secondLevelTitle" placeholder="二级标题"></el-input>
                        </el-form-item>
                        <el-form-item label="描述">
                            <el-input v-model="detailListItem.content" placeholder="描述"></el-input>
                        </el-form-item>
                    </div>
                    <div class="add-item-btn">
                        <el-button type="primary" @click="addDetailItem">添加条目</el-button>
                    </div>
                </el-form-item>
                <el-form-item label="产品详情" prop="detailText" style="display: none">
                    <!-- 工具栏 -->
                    <Toolbar
                        style="border-bottom: 1px solid #ccc"
                        :editor="editor"
                        :defaultConfig="toolbarConfig"
                    />
                    <!-- 编辑器 -->
                    <Editor
                        style="height: 400px; overflow-y: hidden"
                        :defaultConfig="editorConfig"
                        v-model="addForm.detailText"
                        @onChange="onChange"
                        @onCreated="onCreated"
                    />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="onDialogSubmit('modify')" v-if="addForm.id">确认修改</el-button>
                <el-button type="primary" @click="onDialogSubmit('add')" v-else>立即创建</el-button>
            </div>
        </el-dialog>

        <!--   产品富文本详情预览     -->
        <el-dialog title="详细介绍预览" :visible.sync="detailTextDialogVisible" @close="onDialogClose()">
            <div class="detail-text-preview" v-html="currentDetailText"></div>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="detailTextDialogVisible = false">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import { getProductList, addProduct, deleteProduct, getProductDetail, updateProduct } from '@/api/product'
    import { uploadFiles } from '@/api/common'
    import { Editor, Toolbar } from "@wangeditor/editor-for-vue";

    const { createEditor, createToolbar } = window.wangEditor
    export default {
        data() {
            return {
                editor: null,
                toolbarConfig: {
                    /* 显示哪些菜单，如何排序、分组 */
                    toolbarKeys: [
                        'headerSelect',
                        // '|',
                        'bold',
                        'underline',
                        'italic',
                        'color',
                        'bgColor',
                        // '|',
                        'indent',  // 增加缩进
                        'delIndent',  // 减少缩进
                        'justifyLeft',  // 左对齐
                        'justifyRight',  // 右对齐
                        'justifyCenter',  // 居中
                        'justifyJustify',  // 两端对齐
                        // '|',
                        'fontSize',
                        'fontFamily',
                        'lineHeight',
                        // '|',
                        'bulletedList',
                        'numberedList',
                        'todo',
                        'insertLink',
                        'insertTable',
                        // '|',
                        'codeBlock',
                        'divider',
                        'uploadImage',
                        'undo',
                        'redo',
                    ],
                    // excludeKeys: [ ], /* 隐藏哪些菜单 */
                },
                editorConfig: {
                    placeholder: "请输入内容",
                    // autoFocus: false,
                    // readOnly: true, // 只读、不可编辑
                    // 所有的菜单配置，都要在 MENU_CONF 属性下
                    MENU_CONF: {
                        // 配置上传图片
                        uploadImage: {
                            customUpload: this.uploadImgForEditor
                        },
                    },
                },
                searchParams: {
                    pageSize: 10,
                    keyword: '', // 关键词搜索
                    status: '', // 产品状态
                    viewType: '', // 显示类型
                },
                currentPage: 1,
                total: 0,
                tableData: [],
                dialogVisible: false,
                addForm: {
                    bannerPic: '', // 主图
                    firstLevelTitle: '', // 一级标题
                    secondLevelTitle: '', // 二级标题
                    content: '', // 简介
                    jumpUrl: '', // 购买链接
                    status: 2, // 产品状态，1-发布状态；2-草稿状态；3-定时发布状态（默认草稿状态）
                    publishTime: '', // 定时发布时间，状态为3时必填
                    languageType: 'ch', // 语言类型 en:英文 ch:中文
                    viewType: 0, // 显示控制 0：全部 1：PC 2：移动端
                    detailText: '', // 产品介绍富文本
                    productDetailDtoList: [
                        {
                            firstLevelTitle: '',
                            secondLevelTitle: '',
                            content: '',
                            thumbnailPic: ''
                        }
                    ], //
                },
                rules: {
                    id: [
                        {
                            required: false,
                            message: '',
                            trigger: 'blur'
                        },
                    ],
                    viewType: [
                        {
                            required: true,
                            message: '请选择显示端类型',
                            trigger: 'blur'
                        },
                    ],
                    languageType: [
                        {
                            required: true,
                            message: '请选择语言类型',
                            trigger: 'blur'
                        },
                    ],
                    status: [
                        {
                            required: true,
                            message: '请选择产品发布状态',
                            trigger: 'blur'
                        },
                    ],
                    publishTime: [
                        {
                            required: false,
                            message: '请选择产品发布时间',
                            trigger: 'blur'
                        },
                    ],
                    bannerPic: [
                        {
                            required: true,
                            message: '请上传产品主图',
                            trigger: 'blur'
                        },
                    ],
                    thumbnailPic: [
                        {
                            required: true,
                            message: '请上传文章缩略图',
                            trigger: 'blur'
                        },
                    ],
                    firstLevelTitle: [
                        {
                            required: true,
                            message: '一级标题不能为空',
                            trigger: 'blur'
                        }
                    ],
                    secondLevelTitle: [
                        {
                            required: true,
                            message: '二级标题不能为空',
                            trigger: 'blur'
                        }
                    ],
                    content: [
                        {
                            required: true,
                            message: '产品简介不能为空',
                            trigger: 'blur'
                        }
                    ],
                    jumpUrl: [
                        {
                            required: false,
                            message: '产品购买链接不能为空',
                            trigger: 'blur'
                        }
                    ],
                    productDetailDtoList: [
                        {
                            required: true,
                            message: '请添加铲平详情条目',
                            trigger: 'blur'
                        }
                    ],
                },
                dialogTitle: '新增产品',
                detailTextDialogVisible: false, // 产品详情介绍预览弹框
                currentDetailText: '', // 产品详情介绍预览数据
                bannerPicList: [], // 主图列表
                thumbnailPicList: [], // 缩略图列表
            }
        },
        components: { Editor, Toolbar },
        mounted() {
            this.getProductListFn()
        },
        methods: {
            onCreated(editor) {
                this.editor = Object.seal(editor);
            },
            onChange(editor) {
                this.$emit('changeData', this.html)
            },

            // 增加详情条目
            addDetailItem() {
                let newItem = {
                    firstLevelTitle: '',
                    secondLevelTitle: '',
                    content: '',
                    thumbnailPic: ''
                }
                this.addForm.productDetailDtoList.push(newItem)
            },

            // 富文本编辑器上传图片
            async uploadImgForEditor(file, insertFn) {
                let formData = new FormData()
                formData.append('file', file)
                let res = await uploadFiles(formData, {  })
                const { url } = res
                insertFn(url)
            },

            onPageChange(page) {
                this.currentPage = page
            },

            onSearchClick() {
                this.getProductListFn(1)
            },

            // 获取产品列表数据
            async getProductListFn(currentPage) {
                let requestParams = this.searchParams
                requestParams.pageIndex = this.currentPage
                const data = await getProductList(requestParams)
                this.total = +data.total
                this.currentPage = +data.pageIndex || 1
                this.tableData = data.list
            },

            // 显示产品添加弹框
            onDialogOpen() {
                this.dialogVisible=true
            },
            // 关闭产品添加弹窗
            onDialogClose() {
                this.$refs.dataForm.resetFields()
            },

            // 产品添加弹框提交
            onDialogSubmit(type) {
                const { status, publishTime } = this.addForm
                const messageMap = {
                    1: '该产品信息状态即将调整为【发布】状态，官网将显示该条产品信息！',
                    2: '该产品信息状态即将调整为【草稿】状态，官网将不会显示该条产品信息！',
                    3: `该产品信息状态即将调整为【定时发布】状态，官网将于${publishTime}显示该条产品信息！`
                }
                this.$confirm(messageMap[status], '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    if (type === 'modify') {
                        this.modifyProductFn()
                    } else {
                        this.addProductFn()
                    }
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消操作'
                    });
                });
            },

            // 删除已上传的图片
            handleRemove(file, fileList) {
                console.log(file, fileList);
            },

            // 图片上传前校验
            handleBeforeUpload(file) {
                let _this = this;
                return new Promise((resolve, reject) => {
                    let reader = new FileReader()
                    reader.readAsDataURL(file);
                    reader.onload = function () {
                        let img = document.createElement("img");
                        img.src = this.result;
                        img.onload = function () {
                            console.log(img.width)
                            console.log(img.height)
                            let imgRate =  +((img.width / img.height).toFixed(4))
                            if (imgRate === 1.9592) {
                                return resolve(true)
                            } else {
                                _this.$message.error('请上传符合比例的图片!（宽高比：1.9592）');
                                return reject(false)
                            }
                        }
                    }
                })
            },

            // 图片上传成功
            handleUploadSuccess(file) {
                const { code, data, msg } = file
                if (code === 200) {
                    this.addForm.bannerPic = data.url
                } else {
                    this.$message.error(msg)
                }
                console.log(file, '图片上传结果')
            },

            // 图片上传前校验(缩略图)
            handleBeforeUploadSmall(file) {
                let _this = this;
                return new Promise((resolve, reject) => {
                    let reader = new FileReader()
                    reader.readAsDataURL(file);
                    reader.onload = function () {
                        let img = document.createElement("img");
                        img.src = this.result;
                        img.onload = function () {
                            console.log(img.width)
                            console.log(img.height)
                            let imgRate =  +(img.width / img.height)
                            if (imgRate === 1) {
                                return resolve(true)
                            } else {
                                _this.$message.error('请上传符合比例的图片!（宽高比：1）');
                                return reject(false)
                            }
                        }
                    }
                })
            },

            // 图片上传成功(缩略图)
            handleUploadSuccessSmall(file) {
                const { code, data, msg } = file
                if (code === 200) {
                    this.addForm.thumbnailPic = data.url
                } else {
                    this.$message.error(msg)
                }
            },

            // 图片上传成功(详情条目)
            handleUploadSuccessSmallDetailItem(response, file, fileList, index) {
                console.log(response, index)
                const { code, data, msg } = response
                if (code === 200) {
                    this.addForm.productDetailDtoList[index].thumbnailPic = data.url
                } else {
                    this.$message.error(msg)
                }
            },

            // 添加产品
            async addProductFn() {
                let requestParams = this.addForm
                const data = await addProduct(requestParams)
                this.dialogVisible = false
                this.$message.success('产品添加成功')
                this.getProductListFn(1)
                window.location.reload()
            },

            // 修改产品
            async modifyProductFn() {
                let requestParams = this.addForm
                const data = await updateProduct(requestParams)
                this.dialogVisible = false
                this.$message.success('产品修改成功')
                this.getProductListFn(1)
                window.location.reload()
            },

            // 产品编辑
            async handleModify(id) {
                this.dialogVisible = true

                let requestParams = {id}
                let res = await getProductDetail(requestParams)

                this.addForm.id = res.id
                this.addForm.bannerPic = res.bannerPic
                this.addForm.thumbnailPic = res.thumbnailPic
                this.addForm.firstLevelTitle = res.firstLevelTitle
                this.addForm.secondLevelTitle = res.secondLevelTitle
                this.addForm.content = res.content
                this.addForm.typeId = res.typeId
                this.addForm.carousel = res.carousel
                this.addForm.status = res.status
                this.addForm.publishTime = res.publishTime
                this.addForm.languageType = res.languageType
                this.addForm.detailText = res.detailText
                res.productDetailDtoList.map((item, index) => {
                    this.$set(this.addForm.productDetailDtoList, index, item)
                })

                console.log(this.addForm, '))))))')

                this.bannerPicList = [{name: 'bannerPic', url: res.bannerPic}]
                this.thumbnailPicList = [{name: 'thumbnailPic', url: res.thumbnailPic}]
            },

            // 删除产品
            onDeleteClick(id) {
                this.$confirm('此操作将永久删除该产品, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async () => {
                    const data = await deleteProduct({id})
                    this.$message.success('删除成功')
                    this.getProductListFn()
                })
            },

            // 查看产品富文本信息
            onDetailPreviewClick(detailText) {
                this.currentDetailText = detailText
                this.detailTextDialogVisible = true
            },
        }
    }
</script>
<style lang='scss'>
    .list-container{
        .thumbnail{
            width: 100px;
        }
        .detail-text-preview{
            img{
                max-width: 100%;
            }
        }
        .search-area{
            display: flex;
            align-items: center;
            width: 100%;
            padding: 20px 0;
            border-bottom: 1px solid #f2f2f2;
            .search-left{
                display: flex;
                align-items: center;
                justify-content: center;
                .input-line{
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    margin-right: 20px;
                    .label{
                        flex-shrink: 0;
                    }
                    .gap{
                        padding: 0 10px;
                    }
                }
            }
            .search-right{
                display: flex;
                justify-content: flex-end;
                margin-left: 20px;
            }
        }
        .pagination{
            margin-top: 20px;
        }
        .upload-notice{
            color: red;
        }

        .detail-list-container{
            padding: 20px;
            border: 1px solid #e5e5e5;
        }
        .add-item-btn{
            margin-top: 10px;
        }
    }
</style>
